package com.dayu.finecomm.iot.device;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

import javax.net.ssl.SSLContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayu.finecomm.aop.AopProxy;
import com.dayu.finecomm.iot.IotDriverAdapter;
import com.dayu.finecomm.iot.handle.IotPlatInboundHandler;

/**
 * IotPlat驱动, 处理IotPlat协议
 * 
 * @author XuJialiang
 * @since 2017-09-04 10:22:12
 * @version V1.0.0
 */
public class IotPlatDevice extends ChannelInitializer<NioSocketChannel> {
	static Logger LOGGER = LoggerFactory.getLogger(IotPlatDevice.class);

	/**
	 * SSL Context
	 */
	@SuppressWarnings("unused")
	private final SSLContext mSSLCtx;

	/**
	 * Http Server host
	 */
	@SuppressWarnings("unused")
	private String mHost;

	/**
	 * 协议处理适配器
	 */
	private IotDriverAdapter mDriverAdapter = null;

	/**
	 * SSL Peer port
	 */
	@SuppressWarnings("unused")
	private final int mPort;

	public IotPlatDevice(String host, int port, IotDriverAdapter adapter,
			SSLContext sslCtx) {
		mHost = host;
		mPort = port;
		mDriverAdapter = adapter;
		mSSLCtx = sslCtx;
	}

	@Override
	protected void initChannel(NioSocketChannel ctx) throws Exception {

		ChannelPipeline pipeline = ctx.pipeline();

		// SSLEngine sslEngine = mSSLCtx.createSSLEngine();
		// sslEngine.setUseClientMode(false);
		// pipeline.addLast(new SslHandler(sslEngine));

		pipeline.addLast(new HttpRequestDecoder());
		pipeline.addLast(new HttpResponseEncoder());
		pipeline.addLast(new HttpObjectAggregator(16 * 1024));
		IotPlatInboundHandler iotplatHandle = new IotPlatInboundHandler(
				mDriverAdapter);
		iotplatHandle = AopProxy.instance().createAopProxy(
				IotPlatInboundHandler.class, iotplatHandle);
		pipeline.addLast(iotplatHandle);
	}
}
